import logging
import logging.handlers
import os
import time
from datetime import datetime


class LoggerManager:
    def __init__(self, log_dir='app_logs', logger_name='focus_helper'):
        self.log_dir = log_dir
        self.logger = logging.getLogger(logger_name)
        self.logger.setLevel(logging.DEBUG)
        self._setup_logger()

    def _setup_logger(self):
        # 确保日志目录存在
        os.makedirs(self.log_dir, exist_ok=True)

        # 创建格式化器
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

        # 文件处理器 - 按时间轮转
        log_filename = os.path.join(self.log_dir, f'focus_app_{datetime.now().strftime("%Y%m%d")}.log')
        file_handler = logging.handlers.TimedRotatingFileHandler(
            log_filename,
            when='midnight',
            interval=1,
            backupCount=30,
            encoding='utf-8'
        )
        file_handler.setFormatter(formatter)
        file_handler.setLevel(logging.DEBUG)

        # 控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)
        console_handler.setLevel(logging.DEBUG)

        # 添加处理器
        self.logger.addHandler(file_handler)
        self.logger.addHandler(console_handler)

        # 防止日志重复
        self.logger.propagate = False

    def get_logger(self):
        return self.logger


def setup_logger():
    # 创建日志管理器实例
    logger_manager = LoggerManager()
    return logger_manager.get_logger()


def get_logger():
    return logging.getLogger('focus_helper')
